import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/Layout'
import Search from '@/views/Search'
import SearchResult from '@/views/Search/result'
import Home from '@/views/Home'
import Question from '@/views/Question'
import Video from '@/views/Video'
import User from '@/views/User'
import Chat from '@/views/User/chat'
import UserProfile from '@/views/User/userProfile.vue'
import ArticleDetail from '@/views/article'
import store from '@/store'
import { Toast } from 'vant'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/search',
      component: Search
    },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          component: Home,
          meta: {
            isKeepAlive: true
          }
        },
        {
          path: 'question',
          component: Question
        },
        {
          path: 'video',
          component: Video
        },
        {
          path: 'user',
          component: User
        }
      ]
    },
    {
      path: '/searchResult',
      component: SearchResult
    },
    {
      path: '/articleDetail/:id',
      component: ArticleDetail
    },
    {
      path: '/userProfile',
      component: UserProfile
    },
    {
      path: '/userChat',
      component: Chat
    }

  ]
})
// 导航守卫的作用就是根据to.path和token，判断你可以去那个页面（注意：无论怎么样最后都要有next()）
// 需求：配置黑名单，把需要登录的路径配成一个数组，看你是否有token,利用导航守卫进行拦截

const loginUrls = ['/user']
router.beforeEach((to, from, next) => {
  // ...
  if (to.path === '/login' && store.state.user.tokenInfo.token) {
    next('/')
    return
  }
  if (loginUrls.includes(to.path)) {
    if (store.state.user.tokenInfo.token) {
      next()
    } else {
      Toast.fail('您未登录')
      // next('/login')
      router.push({
        path: '/login',
        query: {
          toback: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})

export default router
